#!/usr/bin/env python

import sys
import os

NL=' '
NUM_EPOCH_INDEX=5

def generate_header():
    return ['job :',
            'label   : Copin-IA-projeto2']

def separate_parameters_by_num_epochs(parameters):
    r = {}
    
    for parameter in parameters:
        num_epoch = parameter.split()[NUM_EPOCH_INDEX] 
        if not r.has_key(num_epoch):
            r[num_epoch] = []
        
        r[num_epoch].append(parameter)
    
    return r

def write_to_file(file_name, lines):
    
    h = open(file_name, 'w')
    h.write('\n'.join(lines))
    h.close()
    

def generate_job_for_epoch(epoch, parameters, init_files):
    file_name = 'job-for-epoch-%s.jdf' % epoch
    
    if os.path.exists(file_name):
        raise Exception, 'Output file already exists: %s' % file_name
    
    r = generate_header()
    r += NL
    r += ['init :']
    
    for fr0m, to in init_files:
        r += ['\tput %s %s' % (fr0m, to)]
    
    r += NL
    
    for parameter in parameters:
        r += generate_task(parameter, init_files)
        r += NL
    
    write_to_file(file_name, r)

def generate_job(parameters, init_files):

    parameters_by_num_epochs = separate_parameters_by_num_epochs(parameters)

    for epoch, parameters in parameters_by_num_epochs.iteritems():
        generate_job_for_epoch(epoch, parameters, init_files)

def generate_task(parameter, init_files):
    
    output = parameter.replace(' ','_') + '.out'
    
    r = ['task :']
    r += ['remote: java -jar proj2.jar %s > %s' % (parameter, output)]
    r += ['final: get %s %s' % (output, output)]
    
    return r

def get_put_format(init_files):
    r = []
    for file in init_files:
        r.append((file, os.path.basename(file)))
    return r

def check_files_exists(init_files):
    for file in init_files:
        if not (os.path.exists(file) and os.path.isfile(file)):
            raise Exception, 'File %s does not exist or is not a regular file (i.e. it\'s a directory)' % file

if __name__ == '__main__':
    
    if len(sys.argv) < 2:
        print 'Error! Usage <a file with all combinations of input parameters in each line> <init file 1> [... <init file N>]'
        sys.exit(1)
    
    file_name = sys.argv[1]
    init_files = sys.argv[2:]
    
    h = open(file_name, 'r')
    parameters = [l.strip() for l in h.readlines()]
    h.close()
    
    check_files_exists(init_files)
    init_files = get_put_format(init_files)
    
    generate_job(parameters, init_files)
